package com.gitee.ricesugar.mall.servlets;

import com.gitee.ricesugar.mall.model.POJO.DTO.RegisterDTO;
import com.gitee.ricesugar.mall.model.Service.AccountService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebServlet(name = "RegisterServlet", value = "/register")
public class RegisterServlet extends HttpServlet {

    private AccountService accountService;

    @Override
    public void init() throws ServletException {
        super.init();
        try {
            accountService = new AccountService();
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkCode = request.getParameter("capture");

        HttpSession session = request.getSession();
        if(!checkCode.equals(session.getAttribute("checkCode"))){
            response.sendRedirect("/register.jsp?error=2");
            return;
        }

        try {
            if(accountService.isUsernameExist(username)){
                System.out.println("用户名已存在:" + username);
                response.sendRedirect("/register.jsp?error=1");
                return;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        String regex = "^[a-zA-Z0-9]{4,16}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher userMatcher = pattern.matcher(username);
        Matcher passwordMatcher = pattern.matcher(password);
        if(!userMatcher.matches() || !passwordMatcher.matches()){
            System.out.println("用户名或密码不符合格式:" + username);
            response.sendRedirect("/register.jsp?error=4");
            return;
        }

        RegisterDTO registerDTO = null;
        try {
            registerDTO = accountService.register(username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if(registerDTO != null){
            System.out.println("registerDTO: "+ registerDTO.toString());
            Cookie cookie = new Cookie("login","username=" + username + "password=" + password);
            cookie.setMaxAge(60*60*24);
            response.addCookie(cookie);
            response.sendRedirect("/");
        }else{
            response.sendRedirect("/register.jsp?error=3");
        }
    }
}
